# -*- coding: utf8 -*-
# tests.py
"""
Function attributes:
* load: boolean. Optional. If False the function will not load.
* name: string. Optional.
* priority: string. Optional. Three values are available: "high", "medium" or "low",
  default value: "medium".
* thread: boolean. Optional. If True, function will work by starting a thread.
* rule: string or regexp object. Required.
* aliases: list of string or regexp objects. Optional.
* fullmsg: boolean. Optional. If True, pattern is searched on whole message, else
  pattern is a command, the message must begin with a sign.

* access
* evttypes: must be tuple
* skip_sentinel: skip sentinel instance
* limit
* channels
* url
"""
from core.ircfuncs import *
from util.functions import join_userlist
field = "botops"

def ch_debug(bot, evt, cmd):
	u""".debug +{1|0} +{1|0} +{1|0} → Input Output Buffer"""
	if not has_access(bot, ch_debug.level, evt): return
	bot._debug = tuple([int(arg) == 1 for arg in cmd.arguments])
ch_debug.rule = "debug"
ch_debug.level = "admin"

#Channels
def join_chan_(bot, evt, cmd):
	def check_chan(chan):
		if bot.channels.has_key(chan):
			bot.reply(evt, "I'm already in this channel")
			return True
		return False

	if not has_access(bot, part_chan_.level, evt):
		return  True

	if "@wm" in cmd.arguments:
		wmBot = bot.bots(("slave",1))
		chans = cmd.arguments.split(" ")[1].split(",")
		in_chans = wmBot.channels.keys()
		dont_join=[]
		for chan in list(chans):
			if chan in in_chans:
				dont_join.append(chan)
				chans.remove(chan)
		for chan in chans:
			wmBot.join(chans)
		if dont_join:
			bot.reply(evt, "already on: %s" % ", ".join(dont_join))
		if chans:
			bot.reply(evt, "joined: %s" % ", ".join(dont_join))
		return True

	if " " in cmd.arguments:
		chan = cmd.arguments.split(" ",1)[0]
		msg = cmd.arguments.split(" ",1)[1]
		if check_chan(chan): return True
		bot.join(chan)
		time.sleep(3)
		bot.privmsg(chan, msg)
	else:
		if check_chan(cmd.arguments): return  True
		bot.join(cmd.arguments)
	return True
join_chan_.rule=["j", "join"]
join_chan_.level="support"

def part_chan_(bot, evt, cmd):
	if not has_access(bot, part_chan_.level, evt): return

	def check_chan(chan, rpl=True):
		if not bot.channels.has_key(chan):
			if rpl: bot.reply(evt, "I'm not in this channel")
			return False
		return True

	print "reached part_chan()"
	if " " in cmd.arguments:
		chans, msg = cmd.arguments.split(" ", 1)
		not_in_chan = []
		chans = chans.split(",")
		for chan in list(chans):
			if not check_chan(chan, False):
				not_in_chan.append(chan)
				chans.remove(chan)
		if not_in_chan:
			bot.reply(evt, "I'm not in these channels: $1", ", ".join(not_in_chan))
		bot.part(",".join(chans), msg)
	else:
		#if not check_chan(cmd.arguments and cmd.arguments or ""): return True
		bot.part(cmd.arguments, evt.target)
	return True
part_chan_.rule=["p", "part"]
part_chan_.level = "support"

def other_bots(bot, evt, cmd):
	if not has_access(bot, part_chan_.level, evt): return
	bots_list = bot.logs.otherbots.get()
	if not bots_list:
		bots_file.put([], True)
		bots_list = bots_file.get()
	if cmd.opts['add']:
		if isinstance(cmd.opts['add'], basestring): cmd.opts['add']=[cmd.opts['add']]
		for xbot in cmd.opts['add']:
			if xbot not in bots_list: bots_list.append(xbot)
	elif cmd.opts['rmv']:
		if isinstance(cmd.opts['rmv'], basestring): cmd.opts['rmv']=[cmd.opts['rmv']]
		for xbot in cmd.opts['rmv']:
			if xbot in bots_list: bots_list.remove(xbot)
	bot.logs.otherbots.put(bots_list, True)
	bot.reply(evt, "ignored bots: %s" % join_userlist(bots_list, bot.channels[evt.chan].users(),evt.lang))
other_bots.rule = "otherbots"
other_bots.level = "support"

"""
def quit_(bot, evt, cmd):
   if has_access(bot, "quit", evt):
      msg = "i'll come back, i swear!" if args.cmd == "reboot" else args.params.encode("utf-8") or origin.nick
      self.die(msg)
   else: self.connection.notice(origin.nick, "%s: Only my owner can do this operation." % origin.nick)
f_quit.rule = ['quit', 'reboot']

def go_chans_(bot, evt, cmd):
   if has_access(bot, "join", evt):
		chans = ",".join(self.otherchans)
		self.connection.join(chans)
		self.msg(origin.target, "I've joined channels.")
   else:
      self.connection.notice(origin.nick, "%s: Only my owner can make join me on other channels." % origin.nick)
go_chans_.rule = "gochans"
go_chans_.level = "support"

def allchans(bot, evt, cmd):
   if has_access(bot, "ign", evt):
      if self.channels:
         chans=', '.join(self.channels.keys())
         self.msg(origin.nick, chans)
   else:
      self.msg(origin.nick, "%s: Only staff can use this command." % origin.nick)
f_allchans.rule = 'allchans'

#Users
def ign_(bot, evt, cmd):
   if has_access(bot, "ign", evt):
      params=args.params.strip()
      els=[]
      nousigns=[]
      if ", " in params:
         els=args.split(", ")
      else:
         els=[params]
      if "*" in els: els.remove("*")
      for el in els:
         if "pasqual" in el.lower():
             if origin.host.lower() != "wikipedia/pasqual":
                el=nick
             else:
                self.msg(origin.nick, "je je que cachondo!")
                continue
         if el and el not in self.igns.keys():
             nousigns.append(el)
             self.log("igns", "+ | " + el + " |: " + origin.nick + " :| " + time.strftime("%d-%m-%y %H:%M:%S"))
      if len(nousigns)==1:
         els="el siguiente nick"
      else:
         els="los siguientes nicks"
      if nousigns:
         msg  = u"se ha añadido %s a la lista de ignorados: %s"%(els,', '.join(nousigns))
         self.igns.append(nousigns)
      else:
         igns = ', '.join(self.igns.keys()).encode("utf-8")
         msg  = u"Error: no se han podido añadir los nuevos ignorados, el bot ignorará: %s" % igns
      msg=msg.encode("utf-8")
      self.msg(origin.nick, msg)
   else:
      self.connection.notice(origin.nick, "%s: Only staff can use this command." % origin.nick)
ign_.rule = 'ign'
ign_.level = "support"

def unign_(bot, evt, cmd):
   if has_access(bot, "unign", evt):
      params=args.params.strip().lower()
      els=[]
      elim=[]
      if params=="*":
         self.igns=[]
         self.msg(origin.nick, "se han eliminados todos los registros")
         self.log("igns", "- | all_log |: " + origin.nick + " :| " + time.strftime("%d-%m-%y %H:%M:%S"))
         return
      if ", " in params:
         els=params.split(", ")
      else:
         els=[params]
      for el in els:
         if re.search("\*|\?",el):
            el0=el.replace(".*","*").replace(".?","?").replace("*",".*").replace("?",".?")
            for el1 in self.igns.keys():
               if re.search(r"("+el0+")",el1,re.I):
                  el2=re.search(r"("+el0+")",el1,re.I).group(1)
                  if el1.lower() == el2.lower():
                     elim.append(el1)
         else:
            for el1 in self.igns.keys():
               if el1.lower() == el.lower():
                  elim.append(el1)
      for el in elim:
          self.igns.remove(el)
          self.log("igns", "- | " + el + " |: " + origin.nick + " :| " + time.strftime("%d-%m-%y %H:%M:%S"))
      if elim:
         msg="elementos eliminados: %s"%(', '.join(elim))
         self.msg(origin.nick, msg)
         time.sleep(len(msg)/10)
         msg = "elementos restantes: %s"%(', '.join(self.igns.keys()))
      else:
         msg = "no se han encontrado coincidencias"
      self.msg(origin.nick, msg)
   else:
      self.connection.notice(origin.nick, "%s: Only staff can use this command." % origin.nick)
unign_.rule = 'unign'
unign_.level = 'support'

def igns_(bot, evt, cmd):
   if has_access(bot, "unign", evt):
      if self.igns.keys():
         users=', '.join(self.igns.keys())
         self.msg(origin.nick, users)
      else:
         self.msg(origin.nick, "there are no users ignored.")
   else:
      self.msg(origin.nick, "%s: Only staff can use this command." % origin.nick)
igns_.rule = 'igns'
igns_.level = 'support'

def f_checking(bot, evt, cmd):
   nick = origin.nick if not args.params else args.params.strip()
   self.connection.whois([nick])
f_checking.rule=['check','checking']

#Nickname and account
def nick_(bot, evt, cmd):
	if ordre =="nick" and boss:
			if args:
				c.nick(args.split(" ")[0])
			else:
				c.nick("geni")
nick_.rule=["n", "nick"]
nick_.level = "admin"

def identify_(bot, evt, cmd):
   if has_access(bot, identify_, evt):
      self.msg('NickServ', 'IDENTIFY %s' % self.config.passw)
      self.connection.notice(origin.nick, 'Identified!')
f_identify.rule = "identify"

def ghost_(bot, evt, cmd):
   if has_access(bot, ghost_.level, evt):
      self.msg('NickServ', 'GHOST %s %s' %(self.botnick,self.config.password))
      self.connection.notice(origin.nick, "pampolut has been ghosted!")
ghost_.rule = "ghost"
ghost_.level = "admin"

def group_(bot, evt, cmd):
   c = self.connection
   if has_access(bot, group_.level, evt):
      c.privmsg("NickServ", "group")
   else:
      c.notice(origin.nick, "%s: Only my owner can change my nickname." % origin.nick)
group_.rule = 'group'

def f_chflag(bot, evt, cmd):
   c = self.connection
   newop = args.params.strip().split(" ")[0]
   flag  = args.params.strip().split(" ")[1]
   if has_access(bot, "nick", evt):
	self.accounts.set_flag(newop.encode("utf-8"), flag.encode("utf-8"))
	c.privmsg(self.mainchan, "Now %s is flagged as %s " % (newop, flag))
   else:
      c.notice(origin.nick, "%s: Only my owner can change my nickname." % origin.nick)
f_chflag.rule = 'chflag'

def stalkall(bot, evt, cmd):
	if cmd=="tots" and usuari in moderadors:
		avisals=bot.logs.usersQueue
		if usuari in avisals:
			 avisals.remove(usuari)
		if avisals:
			 usuaris=', '.join(bot.logs.usersQueue)
			 usuaris+=". %s avisa:"%usuari
			 bot.pubmsg("%s"%usuaris)
			 msg = re.sub(r"^tots ","",fullCmd)
			 #msg = fullCmd.split(" ",1)[1])
		else:
			msg=RED+u"Ho sentim, en estos moments no hi ha ningú disponible."+NORMAL
		bot.pubmsg("%s"%msg.encode("utf-8"))

def reboot(bot, evt, cmd):
	if boss:
		self.log("\n[%s] <--! El geni ha estat reiniciat per %s des del canal %s [%s]"%(time.strftime("%y-%m-%d %H:%M:%S"), nick, canal, e.source()))
		self.die("el %s m'ho ha demanat... [%s]" % (nick, canal))
		thread.interrupt_main()
	elif canal == "#wikipedia-ca-patrol" and staff:
		if time.time()-inici>3*60*60:
			print "reboot", time.time()-inici
			self.log("\n[%s] <--! El geni ha estat reiniciat per %s des del canal %s [%s]"%(time.strftime("%y-%m-%d %H:%M:%S"), nick, canal, e.source()))
			self.die("el %s m'ho ha demanat... [%s]" % (nick, canal))
			thread.interrupt_main()
		else:
			h = datetime.datetime.fromtimestamp(inici)+datetime.timedelta(hours=3)
			hread=h++datetime.timedelta(hours=2)
			c.privmsg(canal, "Has d'esperar fins les %s" % hread.strftime("%H:%M:%S"))
	else:
		self.abuso.registracomando(nick,"reboot",3)
		c.privmsg(canal, "Sí home! :P")
re.search("^(reboot|reinicia't)!?$",ev_args.lower())

def die(bot, evt, cmd):
	if re.search(ur"^(die|mor-te|muérete)$", ordre):
			if self.cCC(canal, nick, False, "die", 3): return
			if boss:
				self.die("Ara torne :) ...")
			dau=random.randint(1,3)
			if dau==1:
				c.privmsg(canal, "Mor-te tu, cabró")
			elif dau==2:
				c.privmsg(canal, "Aggghhh em moooooro")
				time.sleep(random.randint(1,5))
				c.privmsg(canal, "Exception: self.die(). Ha estat impossible realitzar l'operació :Þ")
			elif dau==3:
				c.privmsg(canal, "Ui sí, quina poooor... mor-te tu, covard")

def alert(bot, evt, cmd):
	if ordre == ur"alert"  or ordre == ur"tots":
			if self.cCC(canal, nick, False, "tots", 3): return
			usrList = self.channels[canal].users() if canal in self.channels.keys() else []
			if boss:
				for usr in usuaris:
					if re.search(ur'chanserv|ctrl[_-]z|\^d\^|\[d\]ark(?:ito)?_?|francogg_?|geni|rastrojo(?:ut)?_?|'+nick.lower(), usr.lower(), re.I):
						usuaris.remove(usr)
				c.privmsg(canal, string.join(usuaris, ", ")+". El meu amo vos necessita")
			else:
				c.privmsg(canal, "Ordre reservada a gent responsable.")
"""
